package com.eco.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@ServerEndpoint("/eco/{userId}")
@Component
/* loaded from: newfishway-1.0.0-SNAPSHOT.jar:BOOT-INF/classes/com/eco/websocket/WebSocketServer.class */
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger((Class<?>) WebSocketServer.class);
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>(5);
    private Session session;
    private String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info("websocket [{}] is open", userId);
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
        }
    }

    @OnClose
    public void onClose() {
        log.info("websocket [{}] is close", this.userId);
        if (webSocketMap.containsKey(this.userId)) {
            webSocketMap.remove(this.userId);
        }
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("websocket [{}] send message:[{}]", this.userId, message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("websocket [{}] error:[{}]", this.userId, error.getMessage());
    }

    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("send message I/O exception:{}", e.toString());
        }
    }

    public static void sendInfo(String message, @PathParam("userId") String userId) {
        if (!StringUtils.isEmpty(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        }
    }
}